<template>
  <el-dialog
    :title="pageId == 6666?'添加页面':'编辑页面'"
    :visible="isShowDialog"
    @close="btnCancel"
  >
    <!-- 标题 -->
    <el-form ref="pageForm" label-position="top" label-width="80px" :model="formData" :rules="rules">
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title" />
      </el-form-item>
      <!-- 内容 -->
      <el-form-item label="内容" prop="content">
        <vue-editor ref="vueEditor" v-model="formData.content" />
      </el-form-item>

    </el-form>
    <!-- 底部 -->
    <template #footer>
      <el-button type="primary" @click="btnOk">确定</el-button>
      <el-button @click="btnCancel">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { VueEditor } from 'vue2-editor'
import { addPageApi, pageDetailApi, editPageApi } from '@/api/page'
export default {
  components: { VueEditor },
  props: {
    isShowDialog: {
      type: Boolean,
      default: false
    },
    pageId: {
      type: Number,
      default: 6666
    }
  },
  data() {
    return {
      formData: {
        title: '',
        content: '',
        id: ''
      },
      rules: {
        title: [
          { required: true, message: '标题不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '标题要求1-50个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '内容不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '内容描述为1-300个字符', trigger: 'blur' }
        ]
      }
    }
  },
  // 侦听 pageId数据回显
  watch: {
    async pageId() {
      await this.pageDetail()
    }
  },
  methods: {
    async btnOk() {
      // 校验表单
      await this.$refs.pageForm.validate()
      // 发送请求
      if (this.pageId === 6666) {
        // 新增
        await addPageApi(this.formData)
      } else {
        // 编辑
        await editPageApi(this.formData)
      }
      // 提示用户
      this.$message.success('操作成功')
      // 关闭弹窗
      this.$emit('update:isShowDialog', false)
      // 更新页面
      this.$emit('update')
    },
    btnCancel() {
      // 1.清空表单数据
      this.formData = {
        title: '',
        content: '',
        id: ''
      }
      // 2.清空表单校验
      this.$refs.pageForm.resetFields()
      // 3.确保弹窗已关闭
      this.$emit('update:isShowDialog', false)
      this.$parent.pageId = 6666
    },
    // 获取页面详情
    async pageDetail() {
      const { data } = await pageDetailApi(this.pageId)
      this.formData = data
      this.id = data.id
    }
  }
}
</script>

<style>

</style>
